/**
 *@描述：本页面为保存与编辑基本信息页面，其中包含填写标题、摘要、知识分类、关键字、其他描述等信息
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */
import {Button, Typography, message} from 'antd';
import {connect, useDispatch} from 'umi';
import {SaveOutlined} from '@ant-design/icons';
import ProForm, {
    ProFormItem,
    ProFormRadio,
    ProFormList,
    ProFormSelect,
    ProFormText,
    ProFormDependency,
    ProFormDigit,
    ProFormDatePicker,
} from '@ant-design/pro-form';
import BraftEditor from 'braft-editor';
import {useParams} from "umi";
import type {FormListActionType} from '@ant-design/pro-components';

import CustomEditor from '../CustomEditor';

import {
    BaseInfoSaveRequest,
    getClassificationListData, GetKnowledgeBaseInfoRequest,
    getKnowledgeTypesData, KnowledgeCusFieldRequest, SaveTemplateToKnowledgeRequest
} from '@/pages/Dashboard/Knowledge/service';
// import { uniqueId } from 'lodash';
import type {DataNode} from 'antd/es/tree';
import 'braft-editor/dist/index.css';
import styles from './style.less';
import {useEffect, useRef, useState} from "react";
import type {ProFormInstance} from '@ant-design/pro-components';
import {useUpdateEffect} from "ahooks";
import EditableTag from "@/components/ProFormTag";
import CustomTransfer from "@/pages/Dashboard/Knowledge/components/CustomTransfer";
import {IndexModelState} from "@/pages/Dashboard/Knowledge/model";

const {Text} = Typography;

const Basic = (
    {
        title,
        setTitle,
        curSection,
        knowledgeId,
        setKnowledgeId,
        setCurSection,
        structure,
        setStructure,
        KnowledgeObj,
    }: {
        title: string;
        setTitle?: (val: string) => void;
        curSection: AircasKB.Knowledge.SectionItem;
        knowledgeId: string;
        setKnowledgeId?: (val: string) => void;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
        structure?: AircasKB.Knowledge.SectionItem[];
        setStructure?: (val: AircasKB.Knowledge.SectionItem[]) => void;
        KnowledgeObj: IndexModelState;
    }) => {

    const formRef = useRef<ProFormInstance>();
    const {
        type,
    }: {
        type: string;
    } = useParams();

    //TODO:设置页面状态
    const [tags, setTags] = useState<string[]>([]);
    const [loading, setLoading] = useState(false);
    const [editorState, setEditorState] = useState(BraftEditor.createEditorState(""));
    const [initialValue, setInitialValue] = useState<AircasKB.Knowledge.KVView1[]>([]);
    const [defaultValues, setDefaultValues] = useState<AircasKB.Knowledge.KnowledgeCusFieldResponse[]>([]);
    const [targetKeys, setTargetKeys] = useState<string[]>([]);
    const [treeData, setTreeData] = useState<DataNode[]>([]);

    // const dispatch = useDispatch()

    const onChange = (keys: string[]) => {
        setTargetKeys(keys);
    };

    //页面渲染时触发，当知识ID和知识类型变化是触发
    //TODO:userEffect函数
    useEffect(() => {
        getTreeData();
        if (knowledgeId) {
            getKnowledgeBaseInfoRequest(knowledgeId);
        } else {
            getKnowledgeCusField();
        }
    }, [knowledgeId, type])

    //自检更新时自动触发
    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);

    const getTreeData = async () => {
        const res: AircasKB.ResponseType<AircasKB.Knowledge.classificationListResponse[]> = await getClassificationListData({
            parentId: ""
        });
        setTreeData(getSedTree(res.data) || []);
    }

    //获取知识详情，调用GetKnowledgeBaseInfoRequest接口
    //TODO:获取知识详情
    const getKnowledgeBaseInfoRequest = async (id: string) => {
        const res: AircasKB.ResponseType<AircasKB.Knowledge.GetKnowledgeBaseInfoResponse> = await GetKnowledgeBaseInfoRequest({
            id: id
        });
        if (res.code == 200) {
            formRef?.current?.setFieldsValue(res.data);
            const cusFieldViews: AircasKB.Knowledge.KVView1[] = [];
            res.data.cusFieldViews?.map((item) => {
                cusFieldViews.push({
                    label: item.label,
                    value: item.value?.split("@@@")[3].split("000000")[0],
                    k: item.value?.split("@@@")[0]
                })
            })
            setInitialValue(cusFieldViews);
            // @ts-ignore
            setTags(res.data.labels);
            setTargetKeys(res.data.classifications);
            formRef.current?.setFieldsValue({
                other: cusFieldViews,
            })
            setEditorState(BraftEditor.createEditorState(res.data.baseInfo));
        }
    }

    //将其他描述中的初始默认列表加载，加载后根据ID获取某一项的默认值列表
    //TODO:根据ID获取某一项的默认值列表
    const getCusFieldItemsToId = (id: string): AircasKB.Knowledge.KnowledgeCusFieldResponse => {
        let result: AircasKB.Knowledge.KnowledgeCusFieldResponse = {};
        for (let i = 0; i < defaultValues.length; i++) {
            if (defaultValues[i].id == id) {
                result = defaultValues[i];
                break;
            }
        }
        return result;
    }

    //根据知识类型获取其他描述中的列表（自定义列表）,调用KnowledgeCusFieldRequest接口
    //TODO:根据知识类型获取自定义列表
    const getKnowledgeCusField = async () => {
        const res: AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeCusFieldResponse[]> = await KnowledgeCusFieldRequest({knowledgeType: type});
        if (res.code == 200) {
            setDefaultValues(res.data);
            const result: any = [];
            if (res.data.length >= 0) {
                res.data.map((item) => {
                    if (item.isMandatory == "1") {
                        result.push({
                            label: item.label,
                            value: item.id,
                            k: item.value
                        })
                    }
                })
                setInitialValue(result);
                formRef.current?.setFieldsValue({
                    other: result
                })
            }
        }
    }

    //保存当前知识的知识结构模板列表，只在基本信息保存时触发一次，调用SaveTemplateToKnowledgeRequest接口
    //TODO:保存当前知识的知识结构模板列表
    const saveTemplateToKnowledgeRequest = async (knowledgeId: string) => {
        const res: AircasKB.ResponseType<AircasKB.Knowledge.SaveTemplateToKnowledgeResponse[]> = await SaveTemplateToKnowledgeRequest({
            knowledgeId: knowledgeId
        });
        if (res.code == 200) {
            const result: AircasKB.Knowledge.SectionItem[] = [];
            if (res.data.length > 0) {
                res.data.map((item) => {
                    result.push({
                        id: item.id,
                        title: item.title,
                        type: item.type,
                        chapterNo: item.chapterNo
                    })
                })
                setStructure?.(result);
            }
            // message.success("添加成功！");
        }
    }

    //保存按钮触发函数
    //TODO:保存按钮触发函数
    const doSave = async (val:any) => {
        setLoading(true);
        const result: any = formRef.current?.getFieldsValue();
        const customFields: AircasKB.Knowledge.CustomFieldVo[] = [];
        try {
            const customFieldsArr = result[`other`] || [];
            if (customFieldsArr.length > 0) {
                for (let i = 0; i < customFieldsArr.length; i++) {
                    customFields.push({
                        fieldId: customFieldsArr[i].value + '000000' + i,
                        fieldName: "",
                        fieldValue: customFieldsArr[i].k
                    })
                }
            }

            // dispatch({
            //     type: "KnowledgeObj/save",
            //     payload: {
            //         id: knowledgeId,
            //         title: title,
            //         ...result,
            //         baseInfo: editorState.toHTML(),
            //         customFields: customFields,
            //     }
            // })


        } catch (e) {

        }


        //设置保存基本信息的请求参数
        const requestParams:AircasKB.Knowledge.BaseInfoSaveRequestParams = {
            id:knowledgeId,
            title:title,
            ...val,
            baseInfo:editorState.toHTML(),
            customFields:customFields,
        }
        console.log(requestParams);
        // 调用BaseInfoSaveRequest接口，保存基本信息
        const res: AircasKB.ResponseType<AircasKB.Knowledge.BaseInfoSaveResponse> = await BaseInfoSaveRequest(requestParams);
        if(res.code == 200){
            setLoading(false);
            if(!knowledgeId){
                await saveTemplateToKnowledgeRequest(res.data.knowledgeId);
            }
            setKnowledgeId?.(res.data.knowledgeId);
            message.success("保存成功！");
        }
        else{
            setLoading(false);
            message.error("保存失败！");
        }
    }

    //获取目录树结构，使其与组件可识别的结构一致
    const getSedTree = (data?: AircasKB.Knowledge.classificationListResponse[]) => {
        let office = data?.map(item => {
            // @ts-ignore
            const result: any = {
                title: item.name,
                value: item.code,
                key: item.code,
                children: getSedTree(item.childList)
            }
            return result
        })
        return office
    }

    const actionRef = useRef<FormListActionType<{
        label: string;
        value: string;
    }>>();
    return (
        <div className={styles.wrapper}>
            <div className={styles.subTitle}>
                <Text>基本信息</Text>
            </div>
            <ProForm
                formRef={formRef}
                layout="horizontal"
                className={styles.form}
                onFinish={doSave}
                // onValuesChange={doSave}
                labelCol={{
                    style: {
                        width: 80,
                    },
                }}
                submitter={false}
            >
                <ProFormItem
                    label="摘要"
                    required
                    style={{
                        marginBottom: 5,
                    }}
                ></ProFormItem>
                <ProFormItem name="baseInfo"
                             noStyle style={{marginBottom: 20}}>
                    {/*  @ts-ignore */}
                    <CustomEditor value={editorState} onChange={setEditorState} type={type}></CustomEditor>
                    {/*<BraftEditor*/}
                    {/*    className={styles.editor}*/}
                    {/*    extendControls={extendControls}*/}
                    {/*    value={editorState}*/}
                    {/*    onChange={(e)=>handleChange(e)}*/}
                    {/*    placeholder="请输入正文内容"*/}
                    {/*    media={{ uploadFn:uploadHandler, pasteImage: true, onChange: changeImage }}  // 用来定义自己的上传函数*/}
                    {/*/>*/}
                </ProFormItem>
                <br/>
                <ProFormRadio.Group
                    name="type"
                    label="类型"
                    radioType="button"
                    fieldProps={{
                        buttonStyle: 'solid',
                    }}
                    required
                    rules={[
                        {
                            required: true,
                            message: '请选择知识类型',
                        },
                    ]}
                    // options={typeList ?? []}
                    initialValue={type}
                    request={async () => {
                        const list = await getKnowledgeTypesData();
                        return list.map((item) => {
                            if (item.id == type) {
                                return {
                                    label: item.label,
                                    value: item.id,
                                }
                            } else {
                                return {
                                    label: item.label,
                                    value: item.id,
                                    disabled: true,
                                }
                            }
                        });
                    }}
                />
                <ProFormItem name="classifications" label="知识分类" required={true}
                             rules={[
                                 {
                                     validator: async (_, value) => {
                                         const res: any = formRef.current?.getFieldsValue(['classifications']);
                                         if (res.classifications.length > 0) {
                                             return;
                                         }
                                         throw new Error('分类至少要有一项！');
                                     },
                                 },
                             ]}
                >

                    <CustomTransfer
                        dataSource={treeData}
                        targetKeys={targetKeys}
                        onChange={onChange}/>
                    {/*<ProFormTreeSelect*/}
                    {/*    key={uniqueId()}*/}
                    {/*    placeholder="请选择分类"*/}
                    {/*    name="classifications"*/}
                    {/*    fieldProps={{*/}
                    {/*        showSearch: false,*/}
                    {/*        showArrow: true,*/}
                    {/*        treeCheckable:true,*/}
                    {/*        treeDefaultExpandAll:true,*/}
                    {/*        style: {*/}
                    {/*            width: '410px',*/}
                    {/*        },*/}
                    {/*        // showCheckedStrategy:"SHOW_PARENT"*/}
                    {/*    }*/}
                    {/*    }*/}
                    {/*    request={async () => {*/}
                    {/*            const res = await getClassificationListData({parentId:""});*/}
                    {/*            return getSedTree(res.data) || [];*/}
                    {/*    }}*/}
                    {/*/>*/}

                    {/*<Card>*/}

                    {/*    {*/}
                    {/*        list && list?.length>0 &&  list?.map((item)=>{*/}
                    {/*            return (*/}
                    {/*                <ProFormList*/}
                    {/*                    key={uniqueId()}*/}
                    {/*                    name={`fx${item.id}`}*/}
                    {/*                    label={item.name}*/}
                    {/*                    initialValue={[]}*/}
                    {/*                    copyIconProps={false}*/}
                    {/*                    creatorButtonProps={{*/}
                    {/*                        style: { width: 590 },*/}
                    {/*                    }}*/}
                    {/*                >*/}
                    {/*                    <ProFormGroup key={uniqueId()} size="middle">*/}
                    {/*                        <ProFormSelect*/}
                    {/*                            key={uniqueId()}*/}
                    {/*                            name="first"*/}
                    {/*                            placeholder="请选择一级分类"*/}
                    {/*                            style={{ width: 230 }}*/}
                    {/*                            request={async (params: any) => {*/}
                    {/*                                const res = await getClassificationListData({parentId:item.id});*/}
                    {/*                                return res.data.map((item) => ({*/}
                    {/*                                    label: item.name,*/}
                    {/*                                    value: item.code,*/}
                    {/*                                }));*/}
                    {/*                            }}*/}
                    {/*                        />*/}
                    {/*                            <ProFormTreeSelect*/}
                    {/*                            key={uniqueId()}*/}
                    {/*                            name="second"*/}
                    {/*                            placeholder="请选择二级分类"*/}
                    {/*                            dependencies={['first']}*/}
                    {/*                            width={230}*/}
                    {/*                            request={async (params: any) => {*/}
                    {/*                                if(params.first){*/}
                    {/*                                    const res = await getClassificationListDataToCode({code:params.first,type:"0"});*/}
                    {/*                                    return getSedTree(res.data);*/}
                    {/*                                }*/}
                    {/*                                else{*/}
                    {/*                                    return [];*/}
                    {/*                                }*/}

                    {/*                            }}*/}
                    {/*                        />*/}
                    {/*                    </ProFormGroup>*/}
                    {/*                </ProFormList>*/}
                    {/*            )*/}
                    {/*        })*/}
                    {/*    }*/}

                    {/*</Card>*/}
                </ProFormItem>
                <ProFormItem label="关键词" name="labels">
                    <EditableTag value={tags} onChange={setTags}></EditableTag>
                </ProFormItem>
                {/*<ProFormTag label="关键词" name="labels" value={tags}/>*/}
                <ProFormList
                    name="other"
                    label="其他描述"
                    // initialValue={initialValue}
                    min={initialValue.length}
                    actionRef={actionRef}
                    actionGuard={{
                        beforeRemoveRow: async (index, count) => {
                            const row = actionRef.current?.get(index as number);
                            return new Promise((resolve) => {
                                initialValue && initialValue.map((item) => {
                                    // @ts-ignore
                                    if (row.label === item.label) {
                                        resolve(false);
                                        return;
                                    }
                                })
                                resolve(true);
                                // setTimeout(() => resolve(true), 1000);
                            });
                        },
                    }}
                    copyIconProps={false}
                    creatorButtonProps={{
                        style: {width: 415},
                    }}
                    itemContainerRender={(doms) => {
                        return <ProForm.Group>{doms}</ProForm.Group>;
                    }}
                >
                    {(f, index, action) => {
                        return (
                            <>
                                <ProFormSelect
                                    name="value"
                                    placeholder="请选择"
                                    request={async (params: any) => {
                                        const res: AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeCusFieldResponse[]> = await KnowledgeCusFieldRequest({knowledgeType: type});
                                        if (res.code == 200) {
                                            const result: any[] = [];
                                            if (res.data.length >= 0) {
                                                res.data.map((item) => {
                                                    // if(item.isMandatory!="1"){
                                                    result.push({
                                                        label: item.label,
                                                        value: item.id,
                                                        // value:item.value+'@@@'+item.dataType+'@@@'+item.validity+'@@@'+item.id+'@@@'+item.defaultValues,
                                                    })
                                                    // }
                                                })

                                            }
                                            return result;
                                        } else {
                                            return [];
                                        }
                                    }}
                                    style={{width: 193}}
                                />
                                <ProFormDependency key="calc" name={['value']}>
                                    {({value}) => {
                                        const id = value;
                                        const result: AircasKB.Knowledge.KnowledgeCusFieldResponse = getCusFieldItemsToId(id);
                                        if (result) {
                                            if (result.validity == "1") {
                                                const res: any[] = [];
                                                // @ts-ignore
                                                for (let i = 0; i < result.defaultValues?.length; i++) {
                                                    res.push({
                                                        label: result.defaultValues?.[i],
                                                        value: result.defaultValues?.[i]
                                                    })
                                                }
                                                return (
                                                    <ProFormSelect name="k" initialValue={result.value} options={
                                                        res
                                                    }></ProFormSelect>
                                                )
                                            } else {
                                                if (result.dataType === 'string') {
                                                    return (
                                                        <ProFormText
                                                            name="k"
                                                            required={result.validity == "1"}
                                                            initialValue={result.value = "null" ? "" : result.value}
                                                            placeholder="请输入"
                                                            width={190}
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入',
                                                                },
                                                            ]}
                                                        />
                                                    );
                                                }
                                                if (result.dataType === 'number') {
                                                    return (
                                                        <ProFormDigit
                                                            name="k"
                                                            required={result.validity == "1"}
                                                            initialValue={result.value = "null" ? "" : result.value}
                                                            placeholder="请输入"
                                                            width={190}
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入',
                                                                },
                                                            ]}
                                                        ></ProFormDigit>
                                                    );
                                                }
                                                if (result.dataType === 'date') {
                                                    return (
                                                        <ProFormDatePicker
                                                            name="k"
                                                            width={190}
                                                            required={result.validity == "1"}
                                                            initialValue={result.value = "null" ? "" : result.value}
                                                            placeholder="请输入"
                                                            rules={[
                                                                {
                                                                    required: true,
                                                                    message: '请输入',
                                                                },
                                                            ]}
                                                        ></ProFormDatePicker>
                                                    );
                                                }
                                            }

                                        }
                                        return (
                                            <ProFormText
                                                name="k"
                                                required={result.validity == "1"}
                                                initialValue={result.value = "null" ? "" : result.value}
                                                rules={[
                                                    {
                                                        required: true,
                                                        message: '请输入',
                                                    },
                                                ]}
                                                placeholder="请输入"
                                                width={190}
                                            />
                                        );
                                    }}
                                </ProFormDependency>
                            </>
                        );
                    }}
                </ProFormList>
                <ProFormItem>
                    <Button
                        size="large"
                        type="primary"
                        htmlType="submit"
                        icon={<SaveOutlined/>}
                        style={{marginLeft: 80}}
                        loading={loading}
                    >
                        保存
                    </Button>
                </ProFormItem>
            </ProForm>
        </div>
    );
};

// @ts-ignore
const mapStateToProps = ({KnowledgeObj}) => {
    return {
        KnowledgeObj
    };

}
export default connect(mapStateToProps)(Basic);
